package com.example.administrator.testc.DBs;/**
 * Created by Administrator on 2016/5/29 0029.
 */

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.example.administrator.testc.mApp;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>类描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>属性描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>方法描述
 */
public class DownImg extends Thread{

    private String urls;
    public static final String fileath = mApp.getContext().getFilesDir().getAbsolutePath() + "/caches/fileCache";
    public static final String advertisingpath = "/getImage";

    public DownImg(String url){
        this.urls = url;
        init();
    }

    @Override
    public void run() {
        super.run();
        try {
            URL url=new URL(urls);//实例化URL对象url
            HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();//实例化HttpURLConnection对象connection
            httpURLConnection.setConnectTimeout(5000);//设置连接超时时间为5秒
            httpURLConnection.setRequestMethod("GET");//设置请求方法为get方式
            if (httpURLConnection.getResponseCode() == 200) {
                InputStream inputStream = httpURLConnection.getInputStream();
                String fileType = urls.substring(urls.length() - 4);
                try {
                    if(!new File(fileath).exists())
                        new File(fileath).mkdirs();
                    File file = new File(fileath, advertisingpath + fileType);
                    if(file.exists()) {
                        file.delete();
                    }
                    BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(file));
                    BitmapFactory.decodeStream(inputStream).compress(Bitmap.CompressFormat.JPEG, 80, outStream);
                    outStream.flush();
                    outStream.close();
                    Log.i("TAG", "Image saved tosd");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                inputStream.close();
            } else{
                Log.e("TAGSS", "404************");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void init(){
        this.start();
    }
}
